<?php
// 错误报告设置
error_reporting(E_ALL);
ini_set("display_errors", 1);

// 引入自动加载器
require_once("include/Autoloader.php");
Autoloader::register();

// 处理请求
try {
    // 获取请求参数
    $post = !empty($_POST) ? $_POST : $_GET;
    
    // 检查是否有搜索关键词
    if (empty($post['q'])) {
        header('Content-Type: text/html; charset=utf-8');
        exit('?q=关键字');
    }
    
    // 设置响应头
    header("content-Type: application/json; charset=utf-8");
    
    // 准备搜索参数
    $searchParams = [
        'q' => Utils::safeFilter($post['q']),
        'categories' => !empty($post['categories']) ? $post['categories'] : 'general',
        'category_general' => !empty($post['category_general']) ? $post['category_general'] : 1,
        'language' => !empty($post['language']) ? $post['language'] : 'auto',
        'time_range' => !empty($post['time_range']) ? $post['time_range'] : '',
        'safesearch' => !empty($post['safesearch']) ? $post['safesearch'] : '0',
        'theme' => !empty($post['theme']) ? $post['theme'] : 'simple',
        'engines' => !empty($post['engines']) ? $post['engines'] : ''
    ];
    
    // 初始化组件
    $configManager = new ConfigManager();
    $cacheManager = new CacheManager();
    $httpClient = new HttpClient();
    $searchAPI = new SearchAPI($configManager, $cacheManager, $httpClient);
    
    // 执行搜索
    $searchResults = $searchAPI->search($searchParams);
    
    // 返回结果
    if (!empty($searchResults)) {
        $response = [
            'status' => 1,
            'msg' => '搜索成功',
            'list' => $searchResults
        ];
    } else {
        $response = [
            'status' => 1,
            'msg' => '搜索失败'
        ];
    }
    
    // 输出JSON响应
    Utils::jsonResponse($response);
    
} catch (Exception $e) {
    // 处理异常
    Utils::jsonResponse([
        'status' => 0,
        'msg' => '系统错误: ' . $e->getMessage()
    ]);
}